<template>
  <view class="page-wrapper purchase-page page">
    <div class="page-title">选购 Purchase</div>
    <div class="wrap" v-if="proData.id">
      <!-- 商品图片 -->
      <div class="goods-img">
        <img class="img" :src="ossDomain + proData.coverImg" mode="aspectFill" alt="" />
      </div>

      <!-- 商品名称 -->
      <div class="title">
        {{ proData.name }} <br />
        {{ proData.enName }}
      </div>

      <!-- 规格选择 -->
      <div class="li" v-for="(item, index) in proData.specificationJson" :key="index">
        <div class="title">{{ item.groupName }} {{ item.groupEnName }}</div>
        <div class="type-block">
          <div
            class="type-block-item"
            v-for="(skuItem, skuInd) in item.skuList"
            :key="skuInd"
            :class="{
              active: selectedSpecs[item.id] === skuItem.id,
              disabled: !isSpecAvailable(item.id, skuItem.id)
            }"
            @click="selectSpec(item.id, skuItem.id)"
          >
            <div class="type-name">{{ skuItem.name }} {{ skuItem.enName }}</div>
          </div>
        </div>
      </div>
      <!-- 库存 Stockpile -->
      <div class="type-stockpile">库存 Stockpile {{ currentType.id ? currentType.inventory : '--' }}</div>
      <!-- 数量选择 -->
      <div class="title">数量 Quantity</div>
      <div class="te">
        <uv-number-box
          v-model="count"
          :min="1"
          :max="currentType.inventory || 1"
          :step="1"
          @change="valChange"
        ></uv-number-box>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-control-box">
      <div class="bottom-control-container">
        <div class="wrap">
          <div class="left-box">
            <div class="div">¥ {{ totalPrice }}</div>
          </div>
          <div
            class="bottom-control-btn"
            :class="{ disabled: !currentType.id || currentType.inventory === 0 }"
            @click="confirmPurchase"
          >
            确认 Confirm
          </div>
        </div>
        <bottom-safe-area></bottom-safe-area>
      </div>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { proInfo } from '@/utils/api/goods'
import { ossDomain } from '@/utils/oss'
import { onLoad } from '@dcloudio/uni-app'
import { roundNumber } from '@/utils/reg'

const store = useStore()
const vip = computed(() => store.getters['user/isVip'])

const id = ref<string | number>('')
const count = ref<number>(1)
const currentType = ref<any>({})

// 存储用户选择的规格 { 规格组ID: 选择的规格ID }
const selectedSpecs = reactive<Record<string, string>>({})

// 商品数据
const proData = ref<any>({
  // ...保持原有数据结构不变
})

// 计算总价
const totalPrice = computed(() => {
  const discount = vip.value ? 0.9 : 1
  return roundNumber(proData.value.price * count.value * discount, 2)
})

// 选择规格
const selectSpec = (groupId: string, specId: string) => {
  // 如果已经选择了相同的规格，则取消选择
  if (selectedSpecs[groupId] === specId) {
    delete selectedSpecs[groupId]
  } else {
    selectedSpecs[groupId] = specId
  }

  // 检查是否选择了所有规格
  if (Object.keys(selectedSpecs).length === proData.value.specificationJson.length) {
    // 根据选择的规格ID组合查找对应的SKU
    const selectedSpecIds = Object.values(selectedSpecs).sort().join(',')
    const matchedSku = proData.value.skuVos.find(
      (sku: any) => sku.specificationId.split(',').sort().join(',') === selectedSpecIds
    )

    if (matchedSku) {
      currentType.value = matchedSku
      console.log('匹配的SKU:', matchedSku)
    } else {
      currentType.value = {}
      console.warn('未找到匹配的SKU')
    }
  } else {
    currentType.value = {}
  }
}

// 检查规格是否可用（是否有库存）
const isSpecAvailable = (groupId: string, specId: string) => {
  // 临时选择集用于检查
  const tempSelected = { ...selectedSpecs, [groupId]: specId }

  // 如果还没选完所有规格，无法判断
  if (Object.keys(tempSelected).length < proData.value.specificationJson.length) {
    return true
  }

  // 检查是否有匹配的SKU且库存>0
  const selectedSpecIds = Object.values(tempSelected).sort().join(',')
  const matchedSku = proData.value.skuVos.find(
    (sku: any) => sku.specificationId.split(',').sort().join(',') === selectedSpecIds
  )

  return matchedSku && matchedSku.inventory > 0
}

// 确认购买
const confirmPurchase = () => {
  if (!currentType.value.id) {
    return uni.showToast({
      icon: 'none',
      title: '请选择完整规格'
    })
  }

  const info = {
    id: proData.value.id,
    sku: currentType.value,
    count: count.value,
    price: proData.value.price,
    name: proData.value.name,
    enName: proData.value.enName,
    coverImg: proData.value.coverImg
  }

  uni.navigateTo({
    url: '/pages/purchaseConfirm/purchaseConfirm?opt=' + JSON.stringify(info)
  })
}

// 获取商品数据
const getData = async () => {
  const res = await proInfo({ id: id.value })
  if (res.code === 200) {
    res.data.specificationJson = JSON.parse(res.data.specificationJson)
    proData.value = res.data
    console.log('商品数据:', proData.value)
  } else {
    console.log('获取商品信息失败:', res)
  }
}

onLoad((opt) => {
  id.value = opt.id
  getData()
  store.dispatch('user/getUserInfo')
})
</script>
<style lang="scss" scoped>
@import './purchase.scss';

.type-block-item {
  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }

  &.active {
    text-decoration: underline;
  }
}
</style>
